"""
Example: How to Add Real GSI Fortran Function Wrappers

This file demonstrates the process of wrapping actual GSI Fortran
routines for Julia integration.
"""

# ==============================================================================
# Step 1: Identify the Fortran routine signature
# ==============================================================================

# From sigio_module.f90:
#
# subroutine sigio_sropen(lu, cfname, iret)
#   integer(sigio_intkind), intent(in) :: lu
#   character*(*), intent(in) :: cfname
#   integer(sigio_intkind), intent(out) :: iret
# end subroutine

# Symbol name: sigio_module_mp_sigio_sropen_

# ==============================================================================
# Step 2: Create Fortran wrapper with C bindings
# ==============================================================================

# Add to deps/gsi_fortran_wrapper.f90:
#
# subroutine julia_sigio_open(filename, filename_len, lunit, iret) &
#     bind(C, name="julia_sigio_open")
#
#   use sigio_module, only: sigio_sropen
#   integer(c_int), value :: filename_len
#   character(kind=c_char), dimension(filename_len) :: filename
#   integer(c_int), intent(in) :: lunit
#   integer(c_int), intent(out) :: iret
#
#   ! Convert C string to Fortran string
#   character(len=filename_len) :: fortran_filename
#   integer :: i
#
#   do i = 1, filename_len
#     fortran_filename(i:i) = filename(i)
#   end do
#
#   ! Call actual SIGIO routine
#   call sigio_sropen(lunit, fortran_filename, iret)
#
# end subroutine julia_sigio_open

# ==============================================================================
# Step 3: Compile the updated wrapper
# ==============================================================================

# $ cd deps
# $ gfortran -shared -fPIC -o libgsi_wrapper.so \
#       gsi_fortran_wrapper.f90 \
#       gsi_fortran/libsigio.a \
#       -lgfortran

# ==============================================================================
# Step 4: Create Julia wrapper function
# ==============================================================================

const WRAPPER_SO = joinpath(@__DIR__, "..", "deps", "libgsi_wrapper.so")

"""
    sigio_open(filename::String) -> (lunit::Int32, iret::Int32)

Open a SIGIO sigma file and return logical unit number.

# Arguments
- `filename`: Path to sigma file

# Returns
- `lunit`: Logical unit number for subsequent operations
- `iret`: Status code (0 = success)

# Example
```julia
lunit, iret = sigio_open("sigma.f06")
if iret == 0
    println("Successfully opened file on unit \$lunit")
else
    error("Failed to open file: iret = \$iret")
end
```
"""
function sigio_open(filename::String)
    # Convert filename to byte array (C string)
    filename_bytes = Vector{UInt8}(filename)
    filename_len = Int32(length(filename_bytes))

    lunit = Int32(11)  # Fortran logical unit
    iret = Ref{Int32}(0)

    ccall(
        (:julia_sigio_open, WRAPPER_SO),
        Cvoid,
        (Ptr{UInt8}, Int32, Int32, Ref{Int32}),
        filename_bytes, filename_len, lunit, iret
    )

    return lunit, iret[]
end

# ==============================================================================
# Step 5: Test the wrapper
# ==============================================================================

using Test

@testset "SIGIO Wrapper Test" begin
    # Test with a sample sigma file (if available)
    sigma_file = "test_data/sigma.f06"

    if isfile(sigma_file)
        lunit, iret = sigio_open(sigma_file)

        @test iret == 0
        @test lunit > 0

        println("✓ Successfully opened $sigma_file")
        println("  Logical unit: $lunit")
        println("  Status code: $iret")
    else
        @info "Test file not available: $sigma_file"
        @info "Wrapper code is ready but untested"
    end
end

# ==============================================================================
# Complete Example: Full SIGIO Workflow
# ==============================================================================

"""
Complete SIGIO workflow example showing all operations.
"""
function example_sigio_workflow(sigma_file::String)
    println("="^70)
    println("SIGIO Workflow Example")
    println("="^70)

    # 1. Open file
    println("\n[1] Opening file: $sigma_file")
    lunit, iret = sigio_open(sigma_file)

    if iret != 0
        error("Failed to open file: iret = $iret")
    end
    println("    ✓ File opened on unit $lunit")

    # 2. Read header (would need wrapper)
    println("\n[2] Reading header...")
    # header, iret = sigio_read_header(lunit)
    # if iret == 0
    #     println("    ✓ Header read successfully")
    #     println("    - Forecast hour: $(header.fhour)")
    #     println("    - Date: $(header.idate)")
    #     println("    - Levels: $(header.levs)")
    #     println("    - Grid: $(header.lonb) × $(header.latb)")
    # end

    # 3. Read data (would need wrapper)
    println("\n[3] Reading data...")
    # data, iret = sigio_read_data(lunit)
    # if iret == 0
    #     println("    ✓ Data read successfully")
    #     println("    - Temperature size: $(size(data.temperature))")
    # end

    # 4. Close file (would need wrapper)
    println("\n[4] Closing file...")
    # iret = sigio_close(lunit)
    # if iret == 0
    #     println("    ✓ File closed successfully")
    # end

    println("\n" * "="^70)
end

# ==============================================================================
# Template for Other GSI Functions
# ==============================================================================

"""
Template for wrapping additional GSI Fortran functions.

# Process:
1. Identify Fortran routine in GSI source
2. Understand signature and data types
3. Create C-compatible wrapper in gsi_fortran_wrapper.f90
4. Recompile shared library
5. Create Julia ccall wrapper
6. Test with sample data
7. Document usage

# Priority GSI Functions to Wrap:

## SIGIO Module (libsigio.a)
- [ ] sigio_sropen  - Open sigma file
- [ ] sigio_srhead  - Read header
- [ ] sigio_srdata  - Read data
- [ ] sigio_sclose  - Close file

## CRTM Module (libcrtm.a)
- [ ] crtm_init           - Initialize CRTM
- [ ] crtm_forward        - Forward model
- [ ] crtm_adjoint        - Adjoint model
- [ ] crtm_destroy        - Cleanup

## Background Error (berror.f90)
- [ ] read_berror_file    - Load B-matrix
- [ ] load_covariance     - Load eigenvectors

## Quality Control
- [ ] qc_background_check - Background check
- [ ] qc_gross_error     - Gross error check
- [ ] qc_buddy_check     - Buddy check

# Estimated Timeline:
- SIGIO functions: 2 days
- CRTM functions: 3-5 days
- Background error: 2 days
- Quality control: 3 days

Total: ~2 weeks for complete integration
"""

# ==============================================================================
# Best Practices
# ==============================================================================

"""
Best Practices for Fortran-Julia Integration:

1. **Error Handling**
   - Always check return codes (iret)
   - Provide meaningful error messages
   - Use exceptions for fatal errors

2. **Memory Management**
   - Use zero-copy when possible
   - Preallocate output arrays
   - Clean up resources properly

3. **Type Safety**
   - Match Fortran types exactly
   - Use Int32 for Fortran integers
   - Use Float32/Float64 appropriately

4. **Testing**
   - Test with real data files
   - Test edge cases
   - Test error conditions
   - Benchmark performance

5. **Documentation**
   - Document Fortran signature
   - Document Julia interface
   - Provide examples
   - Explain return codes
"""

println("""

How to Add Real GSI Function Wrappers
======================================

This example demonstrates the complete workflow:

1. ✓ Identify Fortran routine signature
2. ✓ Create C-compatible wrapper
3. ✓ Compile to shared library
4. ✓ Create Julia ccall wrapper
5. ✓ Test and document

Next steps:
- Add actual SIGIO wrappers to gsi_fortran_wrapper.f90
- Recompile libgsi_wrapper.so with SIGIO library linked
- Test with real sigma files
- Expand to other GSI modules

See this file for complete template code.
""")
